//
//  YSChildOrderListCtrl.m
//  Yueshi
//
//  Created by Northwan on 15/8/3.
//  Copyright (c) 2015年 悦食中国. All rights reserved.
//

#import "YSChildOrderListCtrl.h"
#import "YSOrderBusinessHeaderView.h"
#import "YSOrderCell.h"
#import "YSOrderListRes.h"
#import "YSMineDataTool.h"
#import "YSCartProduct.h"
#import "YSOrderBusinessFooterView.h"
#import "YSOrderBusinessFooterViewFrame.h"
#import "YSOrderListItemStatusObj.h"
#import "YSAccountCenterCtrl.h"
#import "YSAccountOrderStatusCtrl.h"
#import "YSOrdinaryOrderDetailCtrl.h"
#import "YSExperienceOrderDetailCtrl.h"
#import "YSOrderDeliveryCtrl.h"
#import "YSSupplier.h"
#import "YSBusinessCtrl.h"
#import <objc/runtime.h>
#import "YSOrderReviewCtrl.h"

static const NSString *kAlertOrderCodeObj = @"kAlertOrderCodeObj";

@interface YSChildOrderListCtrl ()<UITableViewDataSource,UITableViewDelegate,YSAccountCenterDelegate,YSAccountOrderStatusDelegate,YSOrderBusinessFooterViewDelegate,UIAlertViewDelegate>
@property (strong, nonatomic) YSCheckLabel *checklabel;
@property (strong, nonatomic) UITableView *tableView;
@property (strong, nonatomic) NSMutableArray *allFrames;
@property (strong, nonatomic) NSMutableArray *footerFrames;
@property (strong, nonatomic) NSMutableArray *orderList;
@property (strong, nonatomic) UIButton *backTopBtn;;
@property (assign, nonatomic) NSInteger pageIndex;
@property (strong, nonatomic) UILabel *nullPageLabel;
@end

@implementation YSChildOrderListCtrl

+(instancetype)initWithCheckLabel:(YSCheckLabel *)checkLabel{
    YSChildOrderListCtrl *controller = [[self alloc]init];
    controller.checklabel = checkLabel;
    return controller;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initTableView];
    
    _nullPageLabel = [UIUtil getPageTipLabelWithTipText:@"暂无订单哦"];
    [_nullPageLabel setHidden:YES];
    [self.view addSubview:_nullPageLabel];
    
    _allFrames = [NSMutableArray array];
    _footerFrames = [NSMutableArray array];
    _orderList = [NSMutableArray array];
    
    _backTopBtn = [[UIButton alloc]init];
    _backTopBtn.frame = CGRectMake(SCREENW-50, _tableView.height-60, 40, 40);
    [_backTopBtn setBackgroundImage:[UIImage imageNamed:@"icon_back_top"] forState:UIControlStateNormal];
    [_backTopBtn setHidden:YES];
    [_backTopBtn addTarget:self action:@selector(toTop:) forControlEvents:UIControlEventTouchUpInside];
    [self.view insertSubview:_backTopBtn aboveSubview:self.tableView];
    
    NSLog(@"%@",self.tableView.superview);
    
}

-(void)toTop:(UIButton *)toTopBtn{
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]
                          atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}

-(void)orderItemBtnClick:(YSOrderListItemStatusObj *)obj{
    if(obj.isLeft){
        switch (obj.status) {
                
            case OrderExperienceVolumeChildNotPayType://待支付
            case OrderOrdinaryChildNotPayType://待支付
                [self cancleOrder:obj.orderCode];
                break;
            case OrderOrdinaryChildNotReceiveType://待收货,已发货
                //查看物流点击
                [self.view.superview.superview.viewController.navigationController pushViewController:[[YSOrderDeliveryCtrl alloc] initWithOrderCode:obj.orderCode] animated:YES];
                break;
            default:
                break;
        }
    }else{
        switch (obj.status) {
            case OrderExperienceVolumeChildNotPayType://体验券待支付
            {
                if(!ISBLANK(obj.orderCode)){
                    YSAccountCenterCtrl *ctrl =  [[YSAccountCenterCtrl alloc]initWithOrdreCode:obj.orderCode  selectProdIds:nil targetType:accountCenterFinishOrderCenterType productType:experienceProductType];
                    [ctrl setDelegate:self];
                    [self.view.superview.superview.viewController.navigationController pushViewController:ctrl animated:YES];
                }
                break;
            }
            case OrderOrdinaryChildNotPayType://美食订单待支付
            {
                if(!ISBLANK(obj.orderCode )){
                    YSAccountCenterCtrl *ctrl =  [[YSAccountCenterCtrl alloc]initWithOrdreCode:obj.orderCode selectProdIds:nil targetType:accountCenterFinishOrderCenterType productType:ordinaryProductType];
                    [ctrl setDelegate:self];
                    [self.view.superview.superview.viewController.navigationController pushViewController:ctrl animated:YES];
                }
                break;
            }
            case OrderOrdinaryChildNotReceiveType://待收货,已发货
            {
                [self enterOrder:obj.orderCode];
                break;
            }
                
            case OrderOrdinaryChildNotReviewType://待评价
                //评论晒单点击
                [self.view.superview.superview.viewController.navigationController pushViewController:[[YSOrderReviewCtrl alloc]initWithOrder:_orderList[obj.tag]] animated:YES];
                break;

            default:
                break;
        }
    }
}

/**
 *  确认收货
 */
-(void)enterOrder:(NSString *)orderCode{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"确认收货" message:@"已收到商品？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [DefaultsHelper setObject:orderCode forKey:kOrderCode];
    [alert setTag:OrderOrdinaryChildNotReceiveType];
    [alert show];
}

/**
 *  确认收货
 */
-(void)enterOrderRequest:(NSString *)orderCode{
    [YSMineDataTool enterWithOrderCode:orderCode success:^(BaseResponse *result) {
        if(result.isSucc){
            [DefaultsHelper setObject:nil forKey:kOrderCode];
            [self requestData];
            [self.tableView reloadData];
            //在这里让其他可以显示这个状态订单的页面也同时刷新,变更这个订单的状态
            [[NSNotificationCenter defaultCenter]postNotificationName:kSubviewsUpdateOrderStatus object:nil];
        }else{
            ShowEnterTips(result.data);
        }
    } failure:^(NSError *error) {
        ShowTips(kRequestFailure);
    }];
}

/**
 *  取消订单
 */
-(void)cancleOrder:(NSString *)orderCode{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"取消订单" message:@"是否取消订单？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [DefaultsHelper setObject:orderCode forKey:kOrderCode];
    [alert setTag:OrderOrdinaryChildNotPayType];
    [alert show];
}

-(void)cancleOrderRequest:(NSString *)orderCode{
    [YSMineDataTool cancleOrderWithOrderCode:orderCode success:^(BaseResponse *result) {
        if(result.isSucc){
            [DefaultsHelper setObject:nil forKey:kOrderCode];
            [self requestData];
            [self.tableView reloadData];
            //在这里让其他可以显示这个状态订单的页面也同时刷新,变更这个订单的状态
            [[NSNotificationCenter defaultCenter]postNotificationName:kSubviewsUpdateOrderStatus object:nil];
        }else{
            ShowEnterTips(result.data);
        }
    } failure:^(NSError *error) {
        ShowTips(kRequestFailure);
    }];
}

-(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        NSString *orderCode = [DefaultsHelper stringForKey:kOrderCode];
        if(alertView.tag == OrderOrdinaryChildNotPayType){//取消订单
            [self cancleOrderRequest:orderCode];
        }else if (alertView.tag == OrderOrdinaryChildNotReceiveType){//确认收货
            [self enterOrderRequest:orderCode];
        }
    }
}


-(void)accountCenterFinish:(int)type status:(NSString *)status{
    if(type == accountCenterFinishOrderCenterType){
        [self toOrderStatusPage:status];
    }
}

/**
 *  结算中心页面关闭,回调跳转至支付状态页面
 *
 *  @param resultCode 状态码
 */
-(void)toOrderStatusPage:(NSString *)resultCode
{
    YSAccountOrderStatusCtrl *ctr = [YSAccountOrderStatusCtrl initWithResultCode:resultCode targetType:orderStatusFinishOrderCenterType];
    ctr.delegate = self;
    //进入状态页面
    [self.view.superview.superview.viewController.navigationController pushViewController:ctr  animated:YES];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if(scrollView.contentOffset.y>scrollView.height*2){
        [_backTopBtn setHidden:NO];
    }else{
        [_backTopBtn setHidden:YES];
    }
}

/**
 *  订单状态页面关闭,回调跳转至订单列表页
 *
 *  @param type
 */
-(void)orderStatusFinish:(int)type
{
    if(orderStatusFinishOrderCenterType == type){
        [self requestData];
    }
}

-(void)initTableView{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 44, SCREENW, SCREENH-NavWithStatusBarH-44) style:UITableViewStylePlain];
    [self.tableView setDelegate:self];
    [self.tableView setDataSource:self];
    [self.tableView setBackgroundColor:PUBLIC_BG];
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
    header.lastUpdatedTimeLabel.hidden = YES;
    _tableView.header = header;
    self.tableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRefresh)];
    
    [self.tableView setTableFooterView:[UIView new]];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.tableView];
}

-(void)headerRefresh{
    self.pageIndex = 0;
    [self requestData];
}

-(void)footerRefresh{
    self.pageIndex++;
    [self requestData];
}

-(void)checkRequestData{
    if(!_orderList.count){
        [self.tableView.header beginRefreshing];
    }
}

-(void)requestData{
    if(ISLOGIN){
         NSString *orderCode = [DefaultsHelper stringForKey:kOrderCode];
        [YSMineDataTool getOrderListWithOrderType:self.view.tag orderCode:orderCode pageIndex:self.pageIndex orderStatus:_checklabel.id success:^(YSOrderListRes *result) {
            [UIUtil refreshComplete:self.tableView];
            if(result.isSucc){
                [DefaultsHelper setObject:nil forKey:kOrderCode];
                if(self.pageIndex == 0){
                    [_orderList removeAllObjects];
                    [_allFrames removeAllObjects];
                    [_footerFrames removeAllObjects];
                }
                if(result.orderList.count){
                    [_orderList addObjectsFromArray:result.orderList];
                    [_allFrames addObjectsFromArray:[self itemArrayWithDeal:result.orderList]];
                    [_footerFrames addObjectsFromArray:[self itemArrayWithFrames:result.orderList]];
                    [self.tableView reloadData];
                }
                
                if(!_allFrames.count){
                    [_nullPageLabel setHidden:NO];
                    [self.tableView setHidden:YES];
                }else{
                    [self.tableView setHidden:NO];
                }
            }else{
                if(result.code == 1001 || result.code == 1002){
                    [Utils clearExitInfo];
                    [Utils showLoginCtrl:self];
                }
                ShowEnterTips(result.data);
            }
        } failure:^(NSError *error) {
            [UIUtil refreshComplete:self.tableView];
            ShowTips(kRequestFailure);
        }];
    }else{
        [UIUtil refreshComplete:self.tableView];
    }
}

/**
 *  处理数据分组
 *
 *  @param orderList 订单列表
 *
 *  @return allFrames
 */
- (NSArray *)itemArrayWithDeal:(NSArray *)orderList
{
    NSMutableArray *frames = [NSMutableArray array];
    for (int i = 0; i<orderList.count; i++) {
        NSArray *prodList = [orderList[i] prodList];
        NSMutableArray *childFrames = [NSMutableArray array];
        for (YSCartProduct *prod in prodList) {
            [childFrames addObject:prod];
        }
        [frames addObject:childFrames];
    }
    return frames;
}

/**
 *  计算footer的frames
 *
 *  @param orderList 订单列表
 *
 *  @return
 */
- (NSArray *)itemArrayWithFrames:(NSArray *)orderList
{
    NSMutableArray *frames = [NSMutableArray array];
    for (int i = 0; i<orderList.count; i++) {
        YSOrderBusinessFooterViewFrame *frame = [[YSOrderBusinessFooterViewFrame alloc]init];
        [frame setOrder:orderList[i]];
        [frames addObject:frame];
    }
    return frames;
}

#pragma  mark - UITableViewDataSource,UITableViewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return  _allFrames.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_allFrames[section] count];
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    YSOrderBusinessHeaderView *headerView = [YSOrderBusinessHeaderView headerView];
   UITapGestureRecognizer *tap =  [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(openBusiness:)];
    [headerView addGestureRecognizer:tap];
    [headerView setWidth:SCREENW];
    [headerView setTag:section];
    if([_orderList[section] supplierLogos]){
        [headerView setOrderWithSupplierIcons:_orderList[section] supplierIcons:[_orderList[section] supplierLogos]];
    }else{
        [headerView setOrder:_orderList[section]];
    }
    return headerView;
}

-(CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return YSOrderBusinessHeaderViewHeight;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    YSOrderBusinessFooterView *footerView = [[YSOrderBusinessFooterView alloc]init];
    [footerView setTag:section];
    [footerView setFooterViewFrame:_footerFrames[section]];
    [footerView setDelegate:self];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(footerClick:)];
    [footerView addGestureRecognizer:tap];
    return footerView;
}

-(CGFloat) tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return [_footerFrames[section] footerViewHeight];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    YSOrderCell *cell =  [YSOrderCell cellWithTableView:tableView];
    cell.product = self.allFrames[indexPath.section][indexPath.row];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return YSOrderCellHeight;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [self toDetail:indexPath.section];
}

-(void)toDetail:(NSInteger)section{
    if( self.view.tag == OrdinaryOrderType){
        YSOrdinaryOrderDetailCtrl *ctrl = [[YSOrdinaryOrderDetailCtrl alloc]initWithOrder:_orderList[section]];
        [self.view.superview.superview.viewController.navigationController pushViewController:ctrl animated:YES];
    }else{
        //体验券
        YSExperienceOrderDetailCtrl *ctrl = [[YSExperienceOrderDetailCtrl alloc]initWithOrder:_orderList[section]];
        [self.view.superview.superview.viewController.navigationController pushViewController:ctrl animated:YES];
    }
}

-(void)openBusiness:(UITapGestureRecognizer *)sender{
    
    YSSupplier *supplier =   _orderList[sender.view.tag];
    if([[_orderList[sender.view.tag] supplierLogos] count]){
        //多个商户点击的时候
    }else{
        NSInteger supplierId =   supplier.supplierId;
        YSBusinessCtrl *ctrl =  [[YSBusinessCtrl alloc]initWithSupplierId:supplierId];
        [self.view.superview.superview.viewController.navigationController pushViewController:ctrl animated:YES];
    }
}

-(void)footerClick:(UIGestureRecognizer *)sender{
    [self toDetail:sender.view.tag];
}

@end
